package com.atbeijing.D05;


import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import java.sql.Timestamp;

/**
 * 分流后开窗前使用KeyedProcessFunction处理每条数据
 *
 * 定时器使用
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost",9999)
                .keyBy(r -> true) //将数据放到同一个流中
                .process(new KeyedProcessFunction<Boolean, String, String>() {
                    //每来一条数据调用一次这个方法
                    @Override
                    public void processElement(String value, Context ctx, Collector<String> out) throws Exception {
                        long time = ctx.timerService().currentProcessingTime();
                        out.collect("数据到达机器时间:"+new Timestamp(time));
                        //开启定时器,5s中后调用onTimer方法
                        ctx.timerService().registerProcessingTimeTimer(time+5*1000);
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        super.onTimer(timestamp, ctx, out);
                        out.collect("定时器触发了，触发时间是：" + new Timestamp(timestamp));
                    }
                })
                .print();

        env.execute();
    }
}
